/**
 * 
 */
package garin.parse;

import java.io.IOException;

public class StringToken extends Token {
	private final String open;
	protected String close;
	private final boolean allowEscape;
	private final boolean allowDoubleQuotingForLiteral;
	private boolean exit;
	protected int ignore = 1;
	
	public StringToken(final Token source, final char quote) {
		this(source, Character.toString(quote));
	}
	
	public StringToken(final Token source, final String open) {
		this(source, open, open, false, true);
	}
	
	public StringToken(final Token source, final String open,
			final String close, final boolean escape,
			final boolean allowDoubleQuotingForLiteral) {
		super(source);
		this.open = open;
		this.close = close;
		allowEscape = escape;
		this.allowDoubleQuotingForLiteral = allowDoubleQuotingForLiteral;
	}
	
	@Override
	public boolean accept() throws IOException {
		return source().is(open);
	}
	
	@Override
	public Token on() throws Exception {
		if (ignore > 0) {
			ignore--;
			return self();
		}
		if (exit) return up();
		if (close.length() == 1 && is(close + close)
				&& allowDoubleQuotingForLiteral) {
			ignore = 1;
			return self();
		}
		if (is(close)) {
			ignore = close.length() - 1;
			exit = true;
			return self();
		}
		if (allowEscape && is('\\')) {
			ignore = 1;
			return self();
		}
		return self();
	}
}
